from fastapi import APIRouter, Request
from starlette.responses import StreamingResponse

from applications.configs.func import render_template
from applications.services.index import login
from applications.schemas.Users import UserLogin
from applications.configs.response import ResponseMessage
from applications.services.power import get_now_user_menus
from applications.services.videos import segmented_transfer

index_router = APIRouter(tags=["主页管理"])


# 主页
@index_router.get("/", summary='主页', description="主页路由")
def index(request: Request):
    return render_template(request, "/home.html", {"powers": get_now_user_menus(request.state.user)})


# 登录页面
@index_router.get("/login", summary='登录页面', description="登录页面")
def login_html(request: Request):
    return render_template(request, "/login.html")


# 登录操作
@index_router.post("/login", summary='登录操作', description="登录操作")
def login_action(login_form: UserLogin):
    code, data = login(login_form)
    return ResponseMessage(code, data)


# 分段传输视频信息
@index_router.get("/videos/{series}/{episode}", summary='分段传输视频信息', description="分段传输视频信息")
def show_videos_contents(series: str, episode: str, request: Request):
    contents, headers = segmented_transfer(series, episode, request)
    if not contents:
        return ResponseMessage(False, "视频不存在")
    # 流式传输
    return StreamingResponse(contents, status_code=206, headers=headers)